package com.czz.portal.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.czz.common.exception.CustomerException;
import com.czz.common.exception.ResultCodeEnum;
import com.czz.portal.config.AlipayConfig;
import com.czz.portal.service.PayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;

/**
 * @ClassName: PayServiceImpl
 * @Author Czz
 * @Date 2020/2/10
 * @Time 10:16
 **/
@Service
public class PayServiceImpl implements PayService {

    /**
    * @Description 生成支付宝订单（订单号，支付金额，订单描述）
    * @Param [orderId, payable, desc]
    * @Return java.lang.String
    * @Author Czz
    * @Date 2020/2/10
    * @Time 10:17
    **/
    @Override
    public String createPay(String orderId, String courseName, BigDecimal payable, String desc) {
        try {
            // 初始化alipayClient
            AlipayClient client = new DefaultAlipayClient (
                    AlipayConfig.gatewayUrl,
                    AlipayConfig.app_id,
                    AlipayConfig.merchant_private_key,
                    AlipayConfig.format,
                    AlipayConfig.charset,
                    AlipayConfig.alipay_public_key,
                    AlipayConfig.sign_type
            );

            // 设置请求参数
            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
            request.setReturnUrl(AlipayConfig.return_url);
            request.setNotifyUrl(AlipayConfig.notify_url);

            // 该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。 该参数数值不接受小数点， 如 1.5h，可转换为 90m。
            String timeout_express = "1h";

            // 构建请求体
            request.setBizContent("{\"out_trade_no\":\"" + orderId + "\","
                    + "\"total_amount\":\"" + payable + "\","
                    + "\"subject\":\"" + courseName + "\","
                    + "\"body\":\"" + desc + "\","
                    + "\"timeout_express\":\"" + timeout_express + "\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

            // 发送请求
            String result = client.pageExecute(request).getBody();
            return result;
        } catch (AlipayApiException e) {
            throw new CustomerException(ResultCodeEnum.CREATE_PAY_ERROR);
        }
    }

    /**
    * @Description 根据订单号查询支付状态
    * @Param [orderId]
    * @Return java.lang.String
    * @Author Czz
    * @Date 2020/2/10
    * @Time 17:48
    **/
    @Override
    public String queryPay(String orderId) {
        // 初始化alipayClient
        AlipayClient client = new DefaultAlipayClient (
                AlipayConfig.gatewayUrl,
                AlipayConfig.app_id,
                AlipayConfig.merchant_private_key,
                AlipayConfig.format,
                AlipayConfig.charset,
                AlipayConfig.alipay_public_key,
                AlipayConfig.sign_type
        );

        // 设置请求参数
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        request.setBizContent("{\"out_trade_no\":\""+ orderId +"\"}");

        // 发送请求
        try {
            String result = client.execute(request).getBody();
            return result;
        } catch (AlipayApiException e) {
            throw new CustomerException(ResultCodeEnum.CREATE_PAY_ERROR);
        }
    }
}
